package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.dto.OrdersDto;
import com.example.entity.OrderDetail;
import com.example.entity.Orders;
import com.example.service.OrdersService;
import com.example.service.impl.OrderDetailServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单表(Orders)表控制层
 *
 * @author makejava
 * @since 2022-05-28 11:56:06
 */
@RestController
@RequestMapping("order")
public class OrdersController {
    /**
     * 服务对象
     */
    @Resource
    private OrdersService ordersService;
    @Resource
    private OrderDetailServiceImpl orderDetailService;
    @PostMapping("/submit")
    public R<String> postSubmit(@RequestBody Orders orders, HttpSession session){
        orders.setUserId((Long) session.getAttribute("user"));
        boolean a=ordersService.submit(orders);
        if(a){
            return R.success("下单成功");
        }else{
            return R.error("下单失败");
        }

    }
    @GetMapping("/userPage")
    public R<Page>pageOfUserPage(int page,int pageSize,HttpSession session){
        Page<Orders>pageInfo=new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders>queryWrapperByOrders=new LambdaQueryWrapper<>();
        queryWrapperByOrders.eq(Orders::getUserId,session.getAttribute("user"));
        queryWrapperByOrders.orderByDesc(Orders::getId);
        ordersService.page(pageInfo,queryWrapperByOrders);
        Page<OrdersDto>pageInfo1=new Page<>();
        BeanUtils.copyProperties(pageInfo,pageInfo1,"records");
        List<Orders> records=pageInfo.getRecords();
        List<OrdersDto>ordersDtoList=records.stream().map((item)->{
            OrdersDto ordersDto=new OrdersDto();
            BeanUtils.copyProperties(item,ordersDto);
            LambdaQueryWrapper<OrderDetail>queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderDetail::getOrderId,item.getId());
            List<OrderDetail>orderDetails=orderDetailService.list(queryWrapper);
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        pageInfo1.setRecords(ordersDtoList);
        return R.success(pageInfo1);
    }
}